// pages/announcements/announcements.js
Page({
  data: {
    announcements: [],
  },

  onLoad() {
    this.loadAnnouncements();
  },

  loadAnnouncements() {
    const db = wx.cloud.database();
    db.collection('announcements').orderBy('timestamp', 'desc').get().then(res => {
      // 格式化时间戳
      const formattedAnnouncements = res.data.map(item => {
        return {
          ...item,
          timestamp: this.formatTimestamp(item.timestamp)
        };
      });

      this.setData({
        announcements: formattedAnnouncements,
      });

      // 更新用户最后查看公告的时间
      wx.cloud.callFunction({
        name: 'updateLastReadAnnouncement',
        data: {
          lastReadAnnouncement: new Date(),
        }
      });
    }).catch(err => {
      wx.showToast({
        title: '加载公告失败',
        icon: 'none',
      });
      console.error('加载公告失败', err);
    });
  },

  formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
});

